package com.suxin.module.http;

import com.suxin.module.MyOpenTSDBConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;

import java.nio.charset.Charset;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Classname HttpClient
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/10/15 15:05
 * @Created by ASUS
 */
@Slf4j
public class MyHttpClient {

    private String host;

    private int port;

    public MyOpenTSDBConfig myOpenTSDBConfig;

    /**
     * 未完成任务数 for graceful close.
     */
    private AtomicInteger unCompletedTask;

    /**
     * 请求http的client
     */
    private CloseableHttpAsyncClient httpClient;

    /**
     * 空闲连接服务
     */
    private ScheduledExecutorService scheduledExecutorService;

    public MyHttpClient(MyOpenTSDBConfig myOpenTSDBConfig) {
        this.myOpenTSDBConfig = myOpenTSDBConfig;
    }

    public MyHttpClient(MyOpenTSDBConfig myOpenTSDBConfig,
                        CloseableHttpAsyncClient httpClient,
                        ScheduledExecutorService scheduledExecutorService) {
        this.host = myOpenTSDBConfig.getHost();
        this.port = myOpenTSDBConfig.getPort();
        this.myOpenTSDBConfig = myOpenTSDBConfig;
        this.httpClient = httpClient;
        this.unCompletedTask = new AtomicInteger(0);
    }

    /**
     * 启动
     */
    public void start() {
        this.httpClient.start();
    }

    public void post(String path, String writeValueAsString,
                     FutureCallback<HttpResponse> futureCallback) {
        log.debug("发送post请求，路径:{},请求内容：{},成功！", path, writeValueAsString);
//        HttpPost httpPost = new HttpPost(getUrl(path));
//        httpPost.addHeader("Content-Type", "application/json");
//        httpPost.setEntity(generateStringEntity(writeValueAsString));
//        this.httpClient.execute(httpPost, null);
    }

    private StringEntity generateStringEntity(String json) {
        return new StringEntity(json, Charset.forName("UTF-8"));
    }

    private String getUrl(String path) {
        return host + ":" + port + path;
    }

}